{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simulation\n",
    "\n",
    "Cirq comes with built-in Python simulators for testing\n",
    "small circuits. The two main types of simulations that Cirq\n",
    "supports are pure state and mixed state. The pure state simulations\n",
    "are supported by ``cirq.Simulator`` and the mixed state\n",
    "simulators are supported by ``cirq.DensityMatrixSimulator``.\n",
    "\n",
    "The names *pure state simulator* and *mixed state\n",
    "simulators* refer to the fact that these simulations are\n",
    "for quantum circuits; including unitary, measurements, and noise\n",
    "that keeps the evolution in a pure state or a mixed state.\n",
    "In other words, there are some noisy evolutions\n",
    "that are supported by the pure state simulator as long as they\n",
    "preserve the purity of the state.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Introduction to pure state simulation\n",
    "\n",
    "Here is a simple circuit:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(0, 0): ───X^0.5───@───X^0.5───M('q0')───\n",
      "                   │\n",
      "(1, 0): ───X^0.5───@───X^0.5───M('q1')───\n"
     ]
    }
   ],
   "source": [
    "import cirq\n",
    "\n",
    "q0 = cirq.GridQubit(0, 0)\n",
    "q1 = cirq.GridQubit(1, 0)\n",
    "\n",
    "def basic_circuit(meas=True):\n",
    "    sqrt_x = cirq.X**0.5\n",
    "    yield sqrt_x(q0), sqrt_x(q1)\n",
    "    yield cirq.CZ(q0, q1)\n",
    "    yield sqrt_x(q0), sqrt_x(q1)\n",
    "    if meas:\n",
    "        yield cirq.measure(q0, key='q0'), cirq.measure(q1, key='q1')\n",
    "\n",
    "circuit = cirq.Circuit()\n",
    "circuit.append(basic_circuit())\n",
    "\n",
    "print(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can simulate this by creating a ``cirq.Simulator`` and\n",
    "passing the circuit into its ``run`` method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "q0=1\n",
      "q1=1\n"
     ]
    }
   ],
   "source": [
    "from cirq import Simulator\n",
    "simulator = Simulator()\n",
    "result = simulator.run(circuit)\n",
    "\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The method `run()` returns an ``TrialResult``.  As you can see, the object `result` contains the result of any measurements for the simulation run.\n",
    "\n",
    "The actual measurement results depend on the seeding from `random` seed generator (`numpy`) . You can set this using ``numpy.random_seed``.\n",
    "\n",
    "Another run, can result in a different set of measurement results:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "q0=0\n",
      "q1=1\n"
     ]
    }
   ],
   "source": [
    "result = simulator.run(circuit)\n",
    "\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The simulator is designed to mimic what running a program\n",
    "on a quantum computer is actually like.  \n",
    "\n",
    "In particular, the ``run()`` methods (``run()`` and ``run_sweep()``) on the simulator do not give access to the wave function of the quantum computer (since one doesn't have access to this on the actual quantum\n",
    "hardware). Instead, the ``simulate()`` methods (``simulate()``,\n",
    "``simulate_sweep()``, ``simulate_moment_steps()``) should be used\n",
    "if one wants to debug the circuit and get access to the full\n",
    "wave function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.5+0.j  0. +0.5j 0. +0.5j 0.5+0.j ]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "circuit = cirq.Circuit()\n",
    "circuit.append(basic_circuit(False))    \n",
    "result = simulator.simulate(circuit, qubit_order=[q0, q1])\n",
    "\n",
    "print(np.around(result.final_state, 3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the simulator uses numpy's ``float32`` precision\n",
    "(which is ``complex64`` for complex numbers) by default,\n",
    "but that the simulator can take in a  `dtype` of `np.complex128`\n",
    "if higher precision is needed.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Qubit and Amplitude Ordering\n",
    "\n",
    "The `qubit_order` argument to the simulator's `run()` method\n",
    "determines the ordering of some results, such as the\n",
    "amplitudes in the final wave function. The `qubit_order` argument is optional: when it is omitted, qubits are ordered\n",
    "ascending by their name (i.e., what their `__str__` method returns).\n",
    "\n",
    "The simplest `qubit_order` value you can provide is a list of\n",
    "the qubits in the desired ordered. Any qubits from the circuit\n",
    "that are not in the list will be ordered using the\n",
    "default `__str__` ordering, but come after qubits that are in\n",
    "the list. Be aware that all qubits in the list are included in\n",
    "the simulation, even if they are not operated on by the circuit.\n",
    "\n",
    "The mapping from the order of the qubits to the order of the\n",
    "amplitudes in the wave function can be tricky to understand.\n",
    "Basically, it is the same as the ordering used by `numpy.kron`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 1  2 10 20]\n"
     ]
    }
   ],
   "source": [
    "outside = [1, 10]\n",
    "inside = [1, 2]\n",
    "print(np.kron(outside, inside))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "More concretely, `k`'th amplitude in the wave function\n",
    "will correspond to the `k`'th case that would be encountered\n",
    "when nesting loops over the possible values of each qubit.\n",
    "\n",
    "The first qubit's computational basis values are looped over\n",
    "in the outermost loop, the last qubit's computational basis\n",
    "values are looped over in the inner-most loop, etc.:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "amps[0] is for first=0, second=0\n",
      "amps[1] is for first=0, second=1\n",
      "amps[2] is for first=1, second=0\n",
      "amps[3] is for first=1, second=1\n"
     ]
    }
   ],
   "source": [
    "i = 0\n",
    "for first in [0, 1]:\n",
    "    for second in [0, 1]:\n",
    "        print('amps[{}] is for first={}, second={}'.format(i, first, second))\n",
    "        i += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can check that this is in fact the ordering with a\n",
    "circuit that flips one qubit out of two:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0. 0. 1. 0.]\n"
     ]
    }
   ],
   "source": [
    "q_stay = cirq.NamedQubit('q_stay')\n",
    "q_flip = cirq.NamedQubit('q_flip')\n",
    "c = cirq.Circuit(cirq.X(q_flip))\n",
    "\n",
    "# first qubit in order flipped\n",
    "result = simulator.simulate(c, qubit_order=[q_flip, q_stay])\n",
    "print(abs(result.final_state).round(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0. 1. 0. 0.]\n"
     ]
    }
   ],
   "source": [
    "# second qubit in order flipped\n",
    "result = simulator.simulate(c, qubit_order=[q_stay, q_flip])\n",
    "print(abs(result.final_state).round(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Stepping through a Circuit\n",
    "\n",
    "When debugging, it is useful to not just see the end\n",
    "result of a circuit, but to inspect, or even modify, the\n",
    "state of the system at different steps in the circuit.  \n",
    "\n",
    "To support this, Cirq provides a method to return an iterator\n",
    "over a ``Moment`` by ``Moment`` simulation.  This method is named ``simulate_moment_steps``:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "state at step 0: [0. +0.5j 0.5+0.j  0.5+0.j  0. -0.5j]\n",
      "state at step 1: [0. +0.5j 0.5+0.j  0.5+0.j  0. +0.5j]\n",
      "state at step 2: [0.5+0.j  0. +0.5j 0. +0.5j 0.5+0.j ]\n",
      "state at step 3: [1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n"
     ]
    }
   ],
   "source": [
    "circuit = cirq.Circuit()\n",
    "circuit.append(basic_circuit())    \n",
    "for i, step in enumerate(simulator.simulate_moment_steps(circuit)):\n",
    "    print('state at step %d: %s' % (i, np.around(step.state_vector(), 3)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The object returned by the ``moment_steps`` iterator is a\n",
    "``StepResult``. This object has the state along with any\n",
    "measurements that occurred **during** that step (so does\n",
    "not include measurement results from previous ``Moments``).\n",
    "\n",
    "In addition, the ``StepResult`` contains ``set_state()``,\n",
    "which  can be used to set the ``state``. One can pass a valid\n",
    "full state to this method by passing a numpy array. Or,\n",
    "alternatively, one can pass an integer, and then the state\n",
    "will be set lie entirely in the computation basis state\n",
    "for the binary expansion of the passed integer.\n",
    "\n",
    "### Monte Carlo simulations of noise\n",
    "\n",
    "Some [noise](noise.ipynb) models can be thought of as randomly\n",
    "applying unitary evolutions with different probabilities. Such\n",
    "noise models are amenable to Monte Carlo simulation. \n",
    "\n",
    "An example of such a noise model is the bit flip channel. This channel\n",
    "randomly applied either does nothing (identity) or applies\n",
    "a Pauli `cirq.X` gate:\n",
    "\n",
    "$\\rho \\rightarrow (1-p) \\rho + p X \\rho X$\n",
    "\n",
    "Let us see an example in a simulator:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({0: 87, 1: 13})\n"
     ]
    }
   ],
   "source": [
    "q = cirq.NamedQubit('a')\n",
    "circuit = cirq.Circuit(cirq.bit_flip(p=0.2)(q), cirq.measure(q))\n",
    "simulator = cirq.Simulator()\n",
    "result = simulator.run(circuit, repetitions=100)\n",
    "print(result.histogram(key='a'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As expected, the bit is flipped about 20 percent of the time.\n",
    "\n",
    "Channels that support this sort of evolution implement the\n",
    "`SupportsMixture` protocol.  Also, note that this functionality\n",
    "is currently only supported in the pure state simulator and\n",
    "not in the density state simulator.  If the mixed state simulator\n",
    "encounters a mixture, it will treat it as a general channel.\n",
    "\n",
    "### Parameterized Values and Studies\n",
    "\n",
    "In addition to circuit gates with fixed values, Cirq also\n",
    "supports gates which can have ``Symbol`` value (see\n",
    "[Gates](gates.ipynb)). These are values that can be resolved\n",
    "at *run-time*. \n",
    "\n",
    "For simulators, these values are resolved by\n",
    "providing a ``ParamResolver``.  A ``ParamResolver`` provides\n",
    "a map from the ``Symbol``'s name to its assigned value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
      "[ 0.6 +0.6j   0.25-0.25j  0.25-0.25j -0.1 -0.1j ]\n",
      "[0. +0.5j 0.5+0.j  0.5+0.j  0. -0.5j]\n",
      "[-0.1 +0.1j   0.25+0.25j  0.25+0.25j  0.6 -0.6j ]\n",
      "[0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n"
     ]
    }
   ],
   "source": [
    "import sympy\n",
    "rot_w_gate = cirq.X**sympy.Symbol('x')\n",
    "circuit = cirq.Circuit()\n",
    "circuit.append([rot_w_gate(q0), rot_w_gate(q1)])\n",
    "for y in range(5):\n",
    "    resolver = cirq.ParamResolver({'x': y / 4.0})\n",
    "    result = simulator.simulate(circuit, resolver)\n",
    "    print(np.round(result.final_state, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we see that the ``Symbol`` is used in two gates, and then the resolver provides this value at run time.\n",
    "\n",
    "Parameterized values are most useful in defining what we call a\n",
    "``Study``.  A ``Study`` is a collection of trials, where each\n",
    "trial is a run with a particular set of configurations and which\n",
    "may be run repeatedly.  \n",
    "\n",
    "Running a `Study` returns one\n",
    "``TrialContext`` and ``TrialResult`` per set of fixed parameter\n",
    "values and repetitions (which are reported as the ``repetition_id``\n",
    "in the ``TrialContext`` object).  \n",
    "\n",
    "For instance:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "q0=00\n",
      "q1=00\n",
      "q0=00\n",
      "q1=11\n",
      "q0=11\n",
      "q1=11\n"
     ]
    }
   ],
   "source": [
    "resolvers = [cirq.ParamResolver({'x': y / 2.0}) for y in range(3)]\n",
    "circuit = cirq.Circuit()\n",
    "circuit.append([rot_w_gate(q0), rot_w_gate(q1)])\n",
    "circuit.append([cirq.measure(q0, key='q0'), cirq.measure(q1, key='q1')])\n",
    "results = simulator.run_sweep(program=circuit,\n",
    "                              params=resolvers,\n",
    "                              repetitions=2)\n",
    "for result in results:\n",
    "    print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Above we see that different repetitions for the case that the\n",
    "qubit has been rotated into a superposition over computational\n",
    "basis states yield different measurement results per run.\n",
    "\n",
    "Also note that we now see the use of the ``TrialContext`` returned\n",
    "as the first tuple from ``run``: it contains the ``param_dict``\n",
    "describing what values were actually used in resolving the ``Symbol`` objects."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Mixed state simulations\n",
    "\n",
    "In addition to pure state simulation, Cirq also supports\n",
    "simulation of mixed states. \n",
    "\n",
    "Even though this simulator is not as efficient as the pure state simulators, they allow for a larger class of noisy circuits to be run as well as keeping track of the simulation's density matrix. This fact can allow for more exact simulations (for example,\n",
    "the pure state simulator's Monte Carlo simulation only\n",
    "allows sampling from the density matrix, not explicitly giving\n",
    "the entries of the density matrix like the mixed state simulator\n",
    "can do). \n",
    "\n",
    "Mixed state simulation is supported by the\n",
    "``cirq.DensityMatrixSimulator`` class.\n",
    "\n",
    "Here is a simple example of simulating a channel using the\n",
    "mixed state simulator:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({0: 64, 1: 36})\n"
     ]
    }
   ],
   "source": [
    "q = cirq.NamedQubit('a')\n",
    "circuit = cirq.Circuit(cirq.H(q), cirq.amplitude_damp(0.2)(q), cirq.measure(q))\n",
    "simulator = cirq.DensityMatrixSimulator()\n",
    "result = simulator.run(circuit, repetitions=100)\n",
    "print(result.histogram(key='a'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We create a state in an equal superposition of 0 and 1,\n",
    "then apply amplitude damping which takes 1 to 0 with\n",
    "something like a probability of 0.2. \n",
    "\n",
    "We see that instead of about 50 percent of the timing being in 0, about 20 percent of the 1 has been converted into 0, so we end up with total\n",
    "around 60 percent in the 0 state.\n",
    "\n",
    "Like the pure state simulators, the mixed state simulator\n",
    "supports ``run()`` and ``run_sweeps()`` methods. \n",
    "\n",
    "The ``cirq.DensityMatrixSimulator`` also supports getting access\n",
    "to the density matrix of the circuit at the end of simulating\n",
    "the circuit, or when stepping through the circuit.  These are\n",
    "done by the ``simulate()`` and ``simulate_sweep()`` methods, or,\n",
    "for stepping through the circuit, via the ``simulate_moment_steps``\n",
    "method.   For example, we can simulate creating an equal\n",
    "superposition followed by an amplitude damping channel with a\n",
    "gamma of 0.2 by:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.6  +0.j 0.447+0.j]\n",
      " [0.447+0.j 0.4  +0.j]]\n"
     ]
    }
   ],
   "source": [
    "q = cirq.NamedQubit('a')\n",
    "circuit = cirq.Circuit(cirq.H(q), cirq.amplitude_damp(0.2)(q))\n",
    "simulator = cirq.DensityMatrixSimulator()\n",
    "result = simulator.simulate(circuit)\n",
    "print(np.around(result.final_density_matrix, 3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We see that we have access to the density matrix at the\n",
    "end of the simulation via ``final_density_matrix``."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}